package sz.szsmk.citizencard.mvp.presenter;

import android.util.Log;
import android.widget.Toast;


import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.youzan.spiderman.utils.Logger;
import com.youzan.spiderman.utils.MD5Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import javax.inject.Inject;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.GsdxNetApi;
import sz.szsmk.citizencard.model.network.bean.request.AccessTokenRequest;
import sz.szsmk.citizencard.model.network.bean.request.AuthorRequest;
import sz.szsmk.citizencard.model.network.bean.request.CheckThirdAppUserReq;
import sz.szsmk.citizencard.model.network.bean.request.GetOrderOpenid;
import sz.szsmk.citizencard.model.network.bean.request.IBaseRequest;
import sz.szsmk.citizencard.model.network.bean.request.LoginRequest;
import sz.szsmk.citizencard.model.network.bean.request.ThirdAppLoginReq;
import sz.szsmk.citizencard.model.network.bean.response.AuthorBean;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.CheckThirdAppUserRes;
import sz.szsmk.citizencard.model.network.bean.response.CloudFlashRes;
import sz.szsmk.citizencard.model.network.bean.response.GestureValidBean;
import sz.szsmk.citizencard.model.network.bean.response.GetOrderOpenidRes;
import sz.szsmk.citizencard.model.network.bean.response.IUserInfo;
import sz.szsmk.citizencard.model.network.bean.response.OauthTokenRes;
import sz.szsmk.citizencard.model.network.bean.response.SeleciUserAuthRes;
import sz.szsmk.citizencard.model.network.bean.response.ThirdAppLoginRes;
import sz.szsmk.citizencard.model.network.bean.response.UserBean;
import sz.szsmk.citizencard.mvp.contract.IAPPMainContact;
import sz.szsmk.citizencard.mvp.contract.ILoginContact;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.newversion.ApiCallback;
import sz.szsmk.citizencard.retrofitrxjava.newversion.HttpDateSource;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.DataStoreUtils;
import sz.szsmk.citizencard.util.IObjectSignatureUtil;
import sz.szsmk.citizencard.util.SIgnUtil;
import sz.szsmk.citizencard.util.Sm4Util;
import sz.szsmk.citizencard.util.StringUtils;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/5/22 15:39
 * description:
 */
public class ILoginPresenter extends IBasePresenter
        implements ILoginContact.ILoginPresenter<ILoginContact.ILoginView> {

    private NetworkDateSources mNetworkDateSource;
    GsdxNetApi gsdxNetApi;
    private String access_token;


    @Inject
    public ILoginPresenter(GsdxNetApi gsdxNetApi) {
        this.gsdxNetApi = gsdxNetApi;
        this.mNetworkDateSource = NetworkDateSources.getInstance();
    }

    @Override
    public void sendMainRequest() {

    }

    @Override
    public void login(final String userPsd, final String userPhone) {
        LoginRequest loginRequest = new LoginRequest();
        String androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns());
        loginRequest.setDevice_id(androidId);

        loginRequest.setPassword(Sm4Util.encryptEcb(userPsd));

        loginRequest.setUser_name(userPhone);
        mNetworkDateSource.login(loginRequest, new SubscribeResult<UserBean>() {
            @Override
            protected void onOk(UserBean response) {
                if (null != response) {
                    ACache.get(DaggerApplication.getIns()).put("userPsd", userPsd);
                    DaggerApplication.setUserBean(response);
                    access_token = response.getAccess_token();
                    L.e(Constant.TAG, "access_token====" + access_token);
                    String refresh_token = response.getRefresh_token();
                    ACache.get(DaggerApplication.getIns()).remove("access_token");
                    //登录以及退出的时候删除协议版本点击信息
                    ACache.get(DaggerApplication.getIns()).remove("protocol_list");
                    ACache.get(DaggerApplication.getIns()).remove("protocolVersion");
                    ACache.get(DaggerApplication.getIns()).put("access_token", access_token);
                    ACache.get(DaggerApplication.getIns()).put("refresh_token", refresh_token);
                    Constant.PHONE = userPhone;
                    getUserInfo();      //获取用户信息
                    getGestureIsOpen(); //获取手势是否开启
                    getGetOrderId();    //获取电子市民卡 授权
                    selectUserAuth(""); //获取 公积金 桂花分 社保状态
                    ((ILoginContact.ILoginView) mView).updataSuccess(response);
                }
                return;
            }

            @Override
            protected void onFailure(UserBean response) {
                super.onFailure(response);
                ((ILoginContact.ILoginView) mView).loginFalie(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                throwable.printStackTrace();
                ((ILoginContact.ILoginView) mView).loginError(throwable.getMessage());
            }
        });

    }

    @Override
    public void author(final String accessToken) {
        AuthorRequest authorRequest = new AuthorRequest();
        String androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns());
        authorRequest.setAccess_token(accessToken);
        authorRequest.setApp_id("50559c6889854850");
        authorRequest.setTimestamp(String.valueOf(System.currentTimeMillis()));
        authorRequest.setSign(SIgnUtil.generateAuthorSign(IObjectSignatureUtil.toMap(authorRequest), "a714998f88ba91177e38e7af43caa949"));
        String json = new Gson().toJson(authorRequest);
        L.e(Constant.TAG, json);
        mNetworkDateSource.author(authorRequest, new SubscribeResult<AuthorBean>() {
            @Override
            protected void onOk(AuthorBean response) {
                Logger.e("AuthorBean == ", response.toString());
                if (null != response) {
                    ((ILoginContact.ILoginView) mView).authorSuccess(response);
                }
                return;
            }

            @Override
            protected void onFailure(AuthorBean response) {
                super.onFailure(response);
                ((ILoginContact.ILoginView) mView).authorFalie(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                throwable.printStackTrace();
                ((ILoginContact.ILoginView) mView).authorError(throwable.getMessage());
            }
        });

    }

    @Override
    public void checkThirdAppUser(final String i, String openid, String androidId) {
        CheckThirdAppUserReq checkThirdAppUserReq = new CheckThirdAppUserReq();
        int parseInt = Integer.parseInt(i);
        checkThirdAppUserReq.setDevice_id(androidId);
        checkThirdAppUserReq.setLogin_type(parseInt);
        checkThirdAppUserReq.setUid(openid);
        String json = new Gson().toJson(checkThirdAppUserReq);
        L.e(Constant.TAG, "checkThirdAppUser----req" + json);
        mNetworkDateSource.checkThirdAppUser(checkThirdAppUserReq, new SubscribeResult<CheckThirdAppUserRes>() {
            @Override
            protected void onOk(CheckThirdAppUserRes response) {
                String json1 = new Gson().toJson(response);
                L.e(Constant.TAG, "checkThirdAppUser----res" + json1);
                ((ILoginContact.ILoginView) mView).checkThirdAppUserSucc(response, i);
            }

            @Override
            protected void onNext(CheckThirdAppUserRes response) {
                super.onNext(response);
                String json2 = new Gson().toJson(response);
                L.e(Constant.TAG, "checkThirdAppUser----res" + json2);
                ((ILoginContact.ILoginView) mView).checkThirdAppUserFail();

            }

            @Override
            protected void onFailure(CheckThirdAppUserRes response) {
                super.onFailure(response);
                ((ILoginContact.ILoginView) mView).checkThirdAppUserFail();
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                ((ILoginContact.ILoginView) mView).checkThirdAppUserFail();
            }
        });
    }

    @Override
    public void oauthToken() {
        IBaseRequest baseRequest = new IBaseRequest();
        baseRequest.setDevice_id(AndroidUtils.getAndroidId(DaggerApplication.getIns()));
        mNetworkDateSource.oauthToken(baseRequest, new SubscribeResult<OauthTokenRes>() {
            @Override
            protected void onOk(OauthTokenRes response) {
                ((ILoginContact.ILoginView) mView).oauthTokenSucc(response);
            }

            @Override
            protected void onFailure(OauthTokenRes response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void thirdAppLogin(int i, String mobile, String setPsdEtSure, String uid) {
        ThirdAppLoginReq thirdAppLoginReq = new ThirdAppLoginReq();
        thirdAppLoginReq.setDevice_id(AndroidUtils.getAndroidId(DaggerApplication.getIns()));
        thirdAppLoginReq.setLogin_type(i);
        thirdAppLoginReq.setMobile(mobile);
        thirdAppLoginReq.setPassword("");
        thirdAppLoginReq.setUid(uid);
        String json = new Gson().toJson(thirdAppLoginReq);
        L.e(Constant.TAG, "------------" + json);
        mNetworkDateSource.thirdAppLogin(thirdAppLoginReq, new SubscribeResult<ThirdAppLoginRes>() {
            @Override
            protected void onOk(ThirdAppLoginRes response) {
                access_token = response.getAccess_token();
                String refresh_token = response.getRefresh_token();
                ACache.get(DaggerApplication.getIns()).put("access_token", access_token);
                ACache.get(DaggerApplication.getIns()).put("refresh_token", refresh_token);

                //第三方登录 成功
                checkSuccessOrderStatus();
                getUserInfo();      //获取用户信息
                getGestureIsOpen(); //获取手势是否开启
                getGetOrderId();    //获取电子市民卡 授权
                selectUserAuth(""); //获取 公积金 桂花分 社保状态

                ((ILoginContact.ILoginView) mView).thirdAppLoginSucc();
            }

            @Override
            protected void onFailure(ThirdAppLoginRes response) {
                super.onFailure(response);
                String json = new Gson().toJson(response);
                L.e(Constant.TAG, "thirdAppLoginFail---->" + json);
                ((ILoginContact.ILoginView) mView).thirdAppLoginFail(response.getMessage());
            }

            @Override
            protected void onNext(ThirdAppLoginRes response) {
                super.onNext(response);
                ((ILoginContact.ILoginView) mView).thirdAppLoginFail(response.getMessage());
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                ((ILoginContact.ILoginView) mView).thirdAppLoginFail(throwable.getMessage());

            }
        });
    }

    @Override
    public void selectUserAuth(String gjj) {
        AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
        mNetworkDateSource.selectUserAuth(accessTokenRequest, new SubscribeResult<SeleciUserAuthRes>() {
            @Override
            protected void onOk(SeleciUserAuthRes response) {
                List<SeleciUserAuthRes.AuthTypeListBean> authTypeList = response.getAuthTypeList();

                /*1.社保 2.公积金 3 桂花分*/
                SeleciUserAuthRes.AuthTypeListBean sbAuth = authTypeList.get(0);
                SeleciUserAuthRes.AuthTypeListBean gjjAuth = authTypeList.get(1);
                SeleciUserAuthRes.AuthTypeListBean ghfAuth = authTypeList.get(2);

                //0 未授权  1.已授权  2.未实名
                Constant.GHF_AUTH = ghfAuth.getIsAuth();
                Constant.SB_AUTH = sbAuth.getIsAuth();
                Constant.GJJ_AUTH = gjjAuth.getIsAuth();

            }

            @Override
            protected void onFailure(SeleciUserAuthRes response) {
                super.onFailure(response);
                Toast.makeText(DaggerApplication.getIns(), response.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void checkSuccessOrderStatus() {

        OkHttpUtils.post()
                .url(Constant.BASE_URL + "app/supply/CheckSuccessOrderStatusReq")
                .addParams("access_token", access_token)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        CloudFlashRes cloudFlashRes = new Gson().fromJson(response, CloudFlashRes.class);
                        if (cloudFlashRes != null) {
                            if (mView != null) {
                                String code = cloudFlashRes.getCode();
                                if (code.equals("000000")) {
                                    String orderStatus = cloudFlashRes.getOrderStatus();
                                    if (orderStatus != null) {
                                        ACache.get(DaggerApplication.getIns()).put("orderStatus", orderStatus);
                                    }
                                    Constant.ORDER_STATUS = orderStatus;
                                    ACache.get(DaggerApplication.getIns()).put("orderStatus", orderStatus);
//                                    ((ISearchAllContact.ISearchAllView) mView).checkSuccessOrderStatusSucc(orderStatus);
                                } else {
//                                    ((ISearchAllContact.ISearchAllView) mView).checkSuccessOrderStatusFail(cloudFlashRes);
                                }
                            }

                        }
                    }
                });


    }

    public void getUserInfo() {
        IBaseRequest userInfoReq = new IBaseRequest();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        userInfoReq.setAccess_token(access_token);
        String androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns());
        userInfoReq.setDevice_id(AndroidUtils.getAndroidId(DaggerApplication.getIns()));
        String refresh_token = ACache.get(DaggerApplication.getIns()).getAsString("refresh_token");
        String key = "access_token=" + access_token + "&device_id=" + androidId + "&key=" + refresh_token;
        String stringMd5 = MD5Utils.getStringMd5(key).toUpperCase();

        userInfoReq.setSign(stringMd5);
//        ObjectSignatureUtil.signatureRequestZhsz(userInfoReq);
        mNetworkDateSource.getUserInfoZhsz(userInfoReq, new SubscribeResult<IUserInfo>() {
            @Override
            protected void onOk(IUserInfo response) {
//                String json = new Gson().toJson(response);
                IUserInfo.UserExBean userEx = response.getUserEx();
                if (userEx != null) {
                    DataStoreUtils.INSTANCE.isLogin().setValue(true);
                    String json = new Gson().toJson(userEx);
                    ACache.get(DaggerApplication.getIns()).put("userId", userEx.getId()+"");
                    ACache.get(DaggerApplication.getIns()).put("mobile", userEx.getMobile());
                    ACache.get(DaggerApplication.getIns()).put("userinfo", json);

                }
//                ((ILoginContact.ILoginView) mView).getUserInfoSucc(response);
            }

            @Override
            protected void onNext(IUserInfo response) {
                super.onNext(response);

            }

            @Override
            protected void onFailure(IUserInfo response) {
                super.onFailure(response);

                String message = response.getMessage();
                ((ILoginContact.ILoginView) mView).updataError(message);

            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    public void getGestureIsOpen() {
        final String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        if (StringUtils.isBlank(access_token)) {
            return;
        }
        IBaseRequest baseRequest = new IBaseRequest();
        baseRequest.setAccess_token(access_token);
        mNetworkDateSource.gestureValid(baseRequest, new SubscribeResult<GestureValidBean>() {
            @Override
            protected void onOk(GestureValidBean response) {
                Constant.isOpen = response.getIsOpen();
            }

            @Override
            protected void onFailure(GestureValidBean response) {
                super.onFailure(response);
            }

            @Override
            protected void onNext(GestureValidBean response) {
                super.onNext(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });
    }

    //获取惠民 拼接参数
    public void getGetOrderId() {
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");

        GetOrderOpenid getOrderOpenid = new GetOrderOpenid();
        getOrderOpenid.setTag("HUIMIN");
        getOrderOpenid.setAccess_token(access_token);
        String json = new Gson().toJson(getOrderOpenid);
        L.e(Constant.TAG, "APPHomePresentergetOrderOpenid----->" + json);
        mNetworkDateSource.getOrderOpenid(getOrderOpenid, new SubscribeResult<GetOrderOpenidRes>() {
            @Override
            protected void onOk(GetOrderOpenidRes response) {
                Constant.EXTENT = response.getExtend();
                ACache.get(DaggerApplication.getIns()).put("mextend", response.getExtend());
            }

            @Override
            protected void onNext(GetOrderOpenidRes response) {
                super.onNext(response);
                String toJson = new Gson().toJson(response);
                L.e(Constant.TAG, "-------------" + toJson);


            }

            @Override
            protected void onFailure(GetOrderOpenidRes response) {
                super.onFailure(response);
                String toJson = new Gson().toJson(response);
                if (response.getCode().equals("0000")) {

                    ACache.get(DaggerApplication.getIns()).remove("mextend");
                    ACache.get(DaggerApplication.getIns()).put("mextend", response.getExtend());
                }
                L.e(Constant.TAG, "-------------" + toJson);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });
    }



}
